from flask import Flask
from flask_marshmallow import Marshmallow
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"]="mysql://root:1@127.0.0.1:3306/mofangapp?charset=utf8mb4"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy()
db.init_app(app)

ma = Marshmallow()
ma.init_app(app)

class User(db.Model):
    __tablename__ = "tb_user"
    id = db.Column(db.Integer, primary_key=True, comment="主键ID")
    name = db.Column(db.String(255), nullable=False, index=True, comment="用户名")
    email = db.String(db.String(255))
    age = db.Column(db.Integer, comment="年龄")
    password = db.Column(db.String(255), comment="登录密码")
    mobile = db.Column(db.String(20), comment="手机号")

    def __repr__(self):
        return "<%s: %s>" % (self.__class__.__name__, self.name)

# 用法1：通过SQLAlchemySchema创建构造器，通过auto从模型中提取字段类型和选项
from marshmallow_sqlalchemy import SQLAlchemySchema,auto_field,SQLAlchemyAutoSchema
from marshmallow import fields,validate
# class UserSchema(SQLAlchemySchema):
#     """模型构造器"""
#     id = auto_field()
#     name = auto_field()
#     password = auto_field()
#     # auto_field在使用过程中，除了可以复制模型对应字段的信息和数据类型以外，我们也可以增加补充说明
#     mobile = auto_field(required=True,validate=validate.Regexp("^1[3-9]\d{9}$"))
#     password2 = fields.String()
#     class Meta:
#         model = User    # 模型类名 table = models.Album.__table__
#         load_instance = True   # 反序列化阶段时，直接返回模型对象
#         include_relationships = True  # 输出模型对象时同时对外键，是否也一并进行处理
#         include_fk = True  # 序列化阶段是否也一并返回主键

class UserSchema(SQLAlchemyAutoSchema):
    mobile = auto_field(required=True, validate=validate.Regexp("^1[3-9]\d{9}$"))
    password2 = fields.String(required=True)
    class Meta:
        model = User    # 模型类名 table = models.Album.__table__
        load_instance = True   # 反序列化阶段时，直接返回模型对象
        include_relationships = True  # 输出模型对象时同时对外键，是否也一并进行处理
        include_fk = True  # 序列化阶段是否也一并返回主键
        sqla_session = db.session # 构造器操作数据库的会话对象
        # fields = ["id","name","mobile","password2"] # 构造器启用的字段列表
        exclude = ["id","name"] # 构造器禁用的字段列表

@app.route("/")
def index():
    user_data = {"mobile":"13312341234","password2":"1234546"}
    us = UserSchema()
    instance = us.load(user_data)
    print(instance)
    return "hello"

if __name__ == '__main__':
    with app.app_context():
        db.drop_all()
        db.create_all()
    app.run(debug=True,host="0.0.0.0",port=5999)